import { t } from 'i18next'
import { useEffect, useState } from 'react'
import dayjs, { WEEKDAY } from '@/plugins/dayjs'
import { DetailInfo, detailUrlParam, domSize } from './interface'
import { FetchMeetingFiles, FetchRegularDetail, FetchMeetingDetail } from '@/api/detail'
import Alert from '@/components/Alert'
import jumpPage from '@/utils/jumpPage'
import { meetingDetailEntity, memberEntity, RoomEntity } from '@/api/detail/interface'
import { useGlobalStore } from '@/store/global'
import { Utils } from '../index/ManageList/MeetingCard/utils'
import { fetchKisCookie, fetchSetCookie, fetchStatus } from '@/api/global'
import { MEETING_JUMP_URL } from '@/utils/constant'
import copy from 'copy-to-clipboard'
import { createRange, getMeetingTime, getRegularMeetingTime } from '@/utils'
import shallow from 'zustand/shallow'

export default function UseTemplateService(data: detailUrlParam) {
	const { user, serverInfo } = useGlobalStore(
		(state) => ({ user: state.user, serverInfo: state.serverInfo }),
		shallow
	)
	const [meeting, setMeeting] = useState<meetingDetailEntity | null>(null)
	const [page, setPage] = useState<DetailInfo>({
		isRepeat: false,
		isAudit: false,
		meeting_moid: '',
		title: {
			name: '',
			isEdit: false,
		},
		time: {
			isShow: false,
			dateTime: '',
		},
		vrm: '',
		regular: {
			isShow: false,
			text: '',
			showLink: false,
			link: '',
		},
		room: {
			isShow: false,
			rooms: [],
			name: '',
			showDetail: false,
			showName: false,
		},
		organizer: '',
		chairman: '',
		e164: '',
		password: '',
		live: {
			liveShow: false,
			liveUrl: '',
			livePasswordShow: false,
			livePassword: '',
			qrCodeBase64Show: false,
			qrCodeBase64: '',
		},
		brief: '',
		file: {
			show: true,
			btnShow: true,
			num: 0,
			text: '',
			showFileManager: false,
		},
		person: {
			attendingPersons: [],
			attendingAllPersons: [],
			notParticipateInAllPersons: [],
			notParticipateInPersons: [],
			showAttendingPersonsMtAll: true,
			showNotParticipateInAllPersonsMtAll: true,
		},
	})
	const [isRepeat, setIsRepeat] = useState(false)
	useEffect(() => {
		if (serverInfo?.enable_kis && user?.enable_kis) {
			fetchKisCookie()
		}
	}, [serverInfo, user])
	useEffect(() => {
		if (!meeting) {
			return
		}
		translateMeeting(meeting)
	}, [meeting, user])
	useEffect(() => {
		// if (!user || !user.account) {
		// 	return
		// }
		if (data.meeting_moid) {
			FetchMeetingFiles(data.meeting_moid).then((res) => {
				//会议详情
				FetchMeetingDetail(data.meeting_moid).then((res) => {
					if (res.success) {
						setMeeting(res)
					} else {
						Alert(t('该会议不存在'), () => {
							jumpPage('meetingList')
						})
					}
				})
			})
		} else if (data.regularMeetingMoid) {
			//例会详情
			FetchRegularDetail(data.regularMeetingMoid).then((res) => {
				if (res.success) {
					setMeeting(res.data)
				} else {
					Alert(t('该会议不存在'), () => {
						jumpPage('meetingList')
					})
				}
			})
		}
	}, [])

	const translateMeeting = (_data: meetingDetailEntity) => {
		const isVideo = _data.video_meeting ? true : false
		const vmr = _data.vmr_name
		const chairman = _data.chairman?.name || ''
		const e164 = _data.conf_id || ''
		const password = _data.password || ''
		const brief = Utils.code.encodeHTML(_data.brief ?? '')
		const name = _data.enable_audience ? t('[超大方]') + `${_data.name}` : `${_data.name}`
		const isRepeat = data.regularMeetingMoid ? true : false
		const isEdit = data.regularMeetingMoid ? false : _data.is_edit ? true : false
		const isRegularMeetingFormular = _data.meeting_formular ? true : false
		const regular = getRegular(isRepeat, isRegularMeetingFormular, _data)
		const time = getDateTime(isRepeat, _data)
		const file = getFileManager(isRepeat, _data)
		const room = getRoom(isRepeat, isVideo, _data)
		const organizer = getOrganizer(_data)
		const live = getLive(_data)
		const person = getPerson(_data)
		setPage({
			isRepeat: isRepeat,
			meeting_moid: _data.meeting_moid || _data.meeting_id,
			title: {
				name,
				isEdit,
			},
			time,
			vrm: vmr,
			regular,
			room,
			organizer,
			chairman,
			e164,
			password,
			live,
			brief,
			file,
			person,
			isAudit: window.location.search.indexOf('audit') > -1 ? true : false,
		})
		setIsRepeat(isRepeat)
	}
	/** 会议人员 */
	const getPerson = (meeting: meetingDetailEntity) => {
		const members = meeting.members ?? []
		let attendingPersons: Array<memberEntity> = []
		let notParticipateInPersons: Array<memberEntity> = []
		let attendingAllPersons: Array<memberEntity> = []
		let notParticipateInAllPersons: Array<memberEntity> = []
		members.map((member) => {
			if (member.is_participated) {
				attendingAllPersons.push(member)
			} else {
				notParticipateInAllPersons.push(member)
			}
			if (
				((meeting.enable_audience && member.interactive_mt) || !meeting.enable_audience) &&
				member.is_participated
			) {
				//超大方会议，默认只展示互动终端
				attendingPersons.push(member)
			} else if (
				((meeting.enable_audience && member.interactive_mt) || !meeting.enable_audience) &&
				!member.is_participated
			) {
				notParticipateInPersons.push(member)
			}
		})
		return {
			attendingPersons,
			attendingAllPersons,
			notParticipateInAllPersons,
			notParticipateInPersons,
			showAttendingPersonsMtAll: true,
			showNotParticipateInAllPersonsMtAll: true,
		}
	}
	/** 会议世博 */
	const getLive = (meeting: meetingDetailEntity) => {
		return {
			liveShow: meeting.live_url ? true : false,
			liveUrl: meeting.live_url ?? '',
			livePasswordShow: meeting.live_password ? true : false,
			livePassword: meeting.live_password || '',
			qrCodeBase64Show: meeting.qr_code_base64 ? true : false,
			qrCodeBase64: meeting.qr_code_base64 ?? '',
		}
	}
	//是否显示全部和收起按钮
	const isShowAllOrStowBtn = (avatar: domSize, attDom: domSize | undefined, notAttDom: domSize | undefined) => {
		/** 参加人员 */
		let isShowAllAttendingPersons = attDom
			? computer(
					page.person.attendingAllPersons.length ?? 0,
					page.person.attendingPersons.length ?? 0,
					avatar,
					attDom
			  )
			: false
		let isShowNotParticipateInAllPersons = notAttDom
			? computer(
					page.person.notParticipateInAllPersons.length ?? 0,
					page.person.notParticipateInPersons.length ?? 0,
					avatar,
					notAttDom
			  )
			: false
		let rowCount = 0
		attDom && (rowCount = (attDom.width - (attDom.width % avatar.width)) / avatar.width)
		return { isShowAllAttendingPersons, isShowNotParticipateInAllPersons, rowCount }
	}
	const computer = (total: number, user: number, li: domSize, parent: domSize) => {
		//超大方会议会隐藏观众席 导致数量不相等
		if (total !== user) {
			return true
		}
		//判断父类高度与子类高度是否相等  相等为一行  不相等为2行
		if (parent.height === li.height) {
			return false
		}
		const rowCount = (parent.width - (parent.width % li.width)) / li.width
		if (user <= rowCount * 2) {
			return false
		}
		return true
	}
	/** 会议室 */
	const getRoom = (isRepeat: boolean, isVideo: boolean, meeting: meetingDetailEntity) => {
		const rooms = meeting.rooms
		if (rooms) {
			const length = rooms.length > 3 ? 3 : rooms.length
			let showDetail = false
			let showName = false
			let meetingRooms = ''
			if (isRepeat || (!isRepeat && isVideo)) {
				showDetail = true
			}
			if (!isRepeat) {
				showName = true
				for (var i = 0; i < length; i++) {
					meetingRooms += (rooms[i] as RoomEntity).name + '，'
				}
				meetingRooms = Utils.code.encodeHTML(Utils.string.removeLastChar(meetingRooms))
			}
			return {
				isShow: rooms.length > 0 ? true : false,
				rooms: rooms ?? [],
				name: meetingRooms,
				showName,
				showDetail,
			}
		}
		return {
			isShow: false,
			rooms: [],
			name: '',
			showName: false,
			showDetail: false,
		}
	}
	/** 文件管理 */
	const getFileManager = (isRepeat: boolean, meeting: meetingDetailEntity) => {
		const day = meeting.start_time ? dayjs(meeting.start_time).format('YYYY-MM-DD') : ''
		const startTime = meeting.start_time ? dayjs(meeting.start_time).format('HH:mm') : '' //会议开始时间
		let actualStartTime = new Date(`${day} ${startTime}`).getTime()
		let nowTime = new Date().getTime()
		//1. 会议中，正在召开; 2. 不是例会；3. 会议后
		let showMeetingSpace = ((nowTime > actualStartTime && meeting.state === 2) || meeting.state === 3) && !isRepeat
		if (isRepeat) {
			if (meeting.file_num == 0) {
				return {
					text: t('无上传文档'),
					num: 0,
					show: user?.enable_upload ? true : false,
					btnShow: false,
					showFileManager: false,
				}
			} else {
				return {
					text: '',
					num: meeting.file_num,
					show: user?.enable_upload ? true : false,
					btnShow: true,
					showFileManager: false,
				}
			}
		} else if (showMeetingSpace) {
			return {
				text: t('会议空间'),
				num: 0,
				show: true,
				btnShow: true,
				showFileManager: false,
			}
		} else {
			return {
				text: '',
				num: meeting.file_num,
				show: user?.enable_upload ? true : false,
				btnShow: true,
				showFileManager: false,
			}
		}
	}
	/** 会议时间 */
	const getDateTime = (isRepeat: boolean, meeting: meetingDetailEntity) => {
		return {
			isShow: !isRepeat,
			dateTime: getMeetingTime(meeting.start_time, meeting.duration, meeting.duration === 0),
		}
	}
	/** 例会 */
	const getRegular = (isRepeat: boolean, isRegularMeetingFormular: boolean, meeting: meetingDetailEntity) => {
		let isShow = false
		let text = ''
		let showLink = false
		let link = ''
		if (isRepeat) {
			isShow = true
			text = getRegularMeetingTime(meeting.start_time, meeting.duration, {
				week_days: meeting.meeting_formular?.week_days ?? '',
				start_date: meeting.meeting_formular?.start_date ?? '',
				end_date: meeting.meeting_formular?.end_date ?? '',
			})
		} else {
			if (isRegularMeetingFormular) {
				isShow = true
				const weekDayLabels = meeting.meeting_formular?.week_days
					? meeting.meeting_formular.week_days
							.split(',')
							.map((item) => WEEKDAY[Number(item)])
							.join('、')
					: ''
				const startDate = meeting.meeting_formular?.start_date
					? dayjs(meeting.meeting_formular.start_date).format('YYYY-MM-DD')
					: ''
				const endDate = meeting.meeting_formular?.end_date
					? dayjs(meeting.meeting_formular.end_date).format('YYYY-MM-DD')
					: ''

				text = t('{{startDate}}开始，到{{endDate}}结束 每周的{{weekDayLabels}}', {
					startDate: startDate,
					endDate: endDate,
					weekDayLabels: weekDayLabels,
				})

				showLink = true
				link =
					'./detail.html?regularMeetingMoid=' +
					(meeting.regular_meeting_moid ? meeting.regular_meeting_moid : meeting.meeting_moid)
			}
		}
		return { isShow, text, showLink, link }
	}
	//发起者
	const getOrganizer = (meeting: meetingDetailEntity) => {
		let organizer = meeting.creator.name + '('
		let telephone = meeting.creator.telephone
		let mobilePhone = meeting.creator.mobile
		if (telephone) {
			organizer += telephone
		}
		if (telephone && mobilePhone) {
			organizer += '/'
		}
		if (mobilePhone) {
			organizer += mobilePhone
		}
		organizer += ')'
		if (!telephone && !mobilePhone) {
			organizer = meeting.creator.name || ''
		}
		return organizer
	}
	const initCopy = (value: string, dom: HTMLElement | null) => {
		copy(value) && createRange(dom)
	}
	const edit = async () => {
		if (!user?.enable_meeting) {
			Alert(t('无会议管理权限，请通知管理员'))
			return
		}
		if (!user?.machine_room_moid) {
			Alert(t('无会议资源，请联系管理员！'))
			return
		}
		fetchStatus(() => {
			if (meeting) {
				const meetingMoid = meeting.meeting_moid
				jumpPage('create', meetingMoid)
			}
		})
	}
	const openFileManage = () => {
		if (!user?.enable_meeting) {
			Alert(t('无会议管理权限，请通知管理员'))
			return
		}
		if (meeting) {
			const day = meeting.start_time ? dayjs(meeting.start_time).format('YYYY-MM-DD') : ''
			const startTime = meeting.start_time ? dayjs(meeting.start_time).format('HH:mm') : '' //会议开始时间
			let actualStartTime = new Date(`${day} ${startTime}`).getTime()
			let nowTime = new Date().getTime()
			let showMeetingSpace =
				((nowTime > actualStartTime && meeting.state === 2) || meeting.state === 3) && !isRepeat
			if (showMeetingSpace) {
				fetchSetCookie(
					{
						meeting_moid: meeting.meeting_moid,
						type: 1,
					},
					() => {
						window.open(MEETING_JUMP_URL + `/meeting/meetingSpace/${meeting.meeting_moid}`)
					}
				)
			} else {
				setPage({
					...page,
					file: {
						...page.file,
						showFileManager: true,
					},
				})
			}
		}
	}
	/** 1 参加人员  2 未参加人员*/
	const showOrHide = (type: number) => {
		if (type === 1) {
			setPage({
				...page,
				person: {
					...page.person,
					showAttendingPersonsMtAll: !page.person.showAttendingPersonsMtAll,
				},
			})
		} else if (type === 2) {
			setPage({
				...page,
				person: {
					...page.person,
					showNotParticipateInAllPersonsMtAll: !page.person.showNotParticipateInAllPersonsMtAll,
				},
			})
		}
	}
	const closeFileManage = (fileNum: number) => {
		setPage({
			...page,
			file: {
				...page.file,
				showFileManager: false,
				num: fileNum,
			},
		})
	}
	const handleShowRoomsDetail = () => {}
	return {
		meeting,
		/** 页面 */
		page,
		/** 复制 */
		initCopy,
		/**编辑*/
		edit,
		/**文件管理*/
		openFileManage,
		/**是否展示全部按钮*/
		isShowAllOrStowBtn,
		/** 收起或者展示全部*/
		showOrHide,
		/**关闭上传文件 */
		closeFileManage,
		/** 会议室详情 */
		handleShowRoomsDetail,
	}
}
